
package hasthi.instrument;

import hasthi.common.constants.HasthiConstants;

import java.lang.management.ManagementFactory;
import java.lang.management.MemoryMXBean;
import java.lang.management.MemoryUsage;
import java.lang.management.ThreadMXBean;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.sun.management.UnixOperatingSystemMXBean;

public class JavaInstrumentation {
    protected static Log log = LogFactory.getLog(HasthiConstants.LOGGER_NAME);
    private static MemoryMXBean memoryMXBean = ManagementFactory.getMemoryMXBean();
    
    public void getOSProperties(){
        com.sun.management.OperatingSystemMXBean osbean = (com.sun.management.OperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();
        osbean.getProcessCpuTime();
//        
//        
//        unixOperatingSystemMXBean.get
        
    }
    
    
    public static String getMemoryUsage(){
        return (memoryMXBean.getHeapMemoryUsage().getUsed()/(1024*1024)) + "MB";
    }

    public static int getThreadCount(){
        return ManagementFactory.getThreadMXBean().getThreadCount();
    }
    
    
    public static double fileDescrypterUsagePercent(){
        try {
            UnixOperatingSystemMXBean unixOperatingSystemMXBean = (com.sun.management.UnixOperatingSystemMXBean)ManagementFactory.getOperatingSystemMXBean();
            return (double)unixOperatingSystemMXBean.getOpenFileDescriptorCount()/unixOperatingSystemMXBean.getMaxFileDescriptorCount();
        } catch (Throwable e) {
            log.error(e.getMessage());
            return -1;
        }
    }

    
    public static double getMemoryUsagePercent(){
        MemoryUsage heapMemoryUsage = memoryMXBean.getHeapMemoryUsage();
        return (double)heapMemoryUsage.getUsed()/heapMemoryUsage.getMax();
//        RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
//        GarbageCollectorMXBean garbageCollectorMXBean = (GarbageCollectorMXBean)ManagementFactory.getGarbageCollectorMXBeans().get(0);
//        garbageCollectorMXBean.get
//        return runtimeMXBean.ge
    }
    
    
    
    public static void main(String[] args) {
        ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();
        ManagementFactory.getMemoryMXBean().getHeapMemoryUsage().getUsed();
    }
}

